package fr.mywiki.business.entry.meta.datatype.text;

import java.text.ParseException;
import java.util.Locale;

import org.jdom.Attribute;
import org.jdom.DataConversionException;
import org.jdom.Element;

import fr.mywiki.business.entry.meta.DataType;
import fr.mywiki.business.resources.ResourceManager;

/** Represents a simple text property, does not have to be interpreted as wiki text. */
public class SimpleText implements DataType {
  public static final String TYPE_NAME = "simpleText";
  
  public static final String TYPE_BUNDLE_KEY = "model.type.simpleText.display";
  public static final String TYPE_BUNDLE_KEY_LIMITED = "model.type.simpleText.display.sizelimit";
  
  /* Xml attributes names */
  public static final String MAX_LENGTH = "maxlength";
  
  /* Possible errors */
  /** Problem of length */
  public static final String INVALID_LENGTH = "model.validation.simpletext.length";
  
  /** The default maximum size for the property */
  public static final int NO_SIZE_LIMIT = 0;
  
	/** The maximum size of the text. If 0 or less, there is no limit. */
	private int maxSize;
	
	public SimpleText() {
		this(NO_SIZE_LIMIT);
	}

	public SimpleText(int maxSize) {
		setMaxSize(maxSize);
	}

	public int getMaxSize() {
		return maxSize;
	}
	
	public boolean isSizeLimited() {
		return maxSize > NO_SIZE_LIMIT;
	}

	public void setMaxSize(int maxSize) {
		if (maxSize < NO_SIZE_LIMIT)
			this.maxSize = NO_SIZE_LIMIT;
		this.maxSize = maxSize;
	}

  public String getTypeName() {
   return TYPE_NAME;
  }
  
  public String getDisplayKey() {
  	return TYPE_BUNDLE_KEY;
  }

	public String checkValue(Object value) {
		if (maxSize < 1)
			// No size limit, always ok
			return null;
		
		if(maxSize < value.toString().length())
			return INVALID_LENGTH;
		
		return null;
	}

	/**
	 * Format : "Simple text [limited to n chars]".
	 */
	public String describe(Locale locale) {
		StringBuffer buffer = new StringBuffer();
		
		buffer.append(ResourceManager.getMessage(TYPE_BUNDLE_KEY, locale));
		if (maxSize > NO_SIZE_LIMIT)
			buffer.append(" "
					+ ResourceManager.getMessage(TYPE_BUNDLE_KEY_LIMITED, locale,
							new String[] { Integer.toString(maxSize) }));
		
		return buffer.toString();
	}

	public void describeXml(Element elt) {
		if(isSizeLimited())
			elt.addAttribute(MAX_LENGTH, getMaxSize() + "");
	}

	public void fillFromXml(Element elt) {
		Attribute attr = elt.getAttribute(MAX_LENGTH);
		if(attr!=null)
			try {
				setMaxSize(attr.getIntValue());
			} catch (DataConversionException e) {
				e.printStackTrace();
			}
	}

	public Object getValue(String strVal) throws ParseException {
		return strVal;
	}
}
